package com.example.iwalk.newprintapplication.util;

import android.util.Log;

import com.example.iwalk.newprintapplication.imp.NetSocket;
import com.example.iwalk.newprintapplication.inter.IpCatcher;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class IpCatchThread extends Thread {
    private int finishSize = 0;
    private ScheduledExecutorService pool;
    private boolean isFinish;
    private long lastFinishTime;
    private String ipStr;
    private IpCatcher ipCatcher;

    public IpCatchThread(String ipStr, IpCatcher ipCatcher) {
        this.ipStr = ipStr;
        this.ipCatcher = ipCatcher;
    }

    @Override
    public void run() {
        if (pool == null) {
            pool = Executors.newScheduledThreadPool(100);
        }
        for (int i = 2; i < 255; ++i) {
            if (i == 2) {
                ipCatcher.onCatchStart();
            }
            final int index = i;
            pool.execute(new Runnable() {
                @Override
                public void run() {
                        try {
                            String[] ipStrs = ipStr.split("\\.");
                            String ipaddress = ipStrs[0] + "." + ipStrs[1] + "." + ipStrs[2] + "." + index;
                            NetSocket netSocket = new NetSocket();
                            netSocket.Open(ipaddress, NetSocket.POS_OPEN_NETPORT);
                            if (netSocket.IFOpen) {
                                ipCatcher.onIpCatched(ipaddress);
                            } else {
                            }
//                        Thread.sleep(100);
                        } catch (Exception e) {
                        } finally {
                            synchronized ("") {
                            finishSize++;
                                Log.e("sdf","finishSize"+finishSize);
                            if (finishSize == 253) {
                                ipCatcher.onCatchFinish();
                            }
                        }
                    }
                }
            });
        }
//            while (true) {
//                synchronized (this) {
//                    Log.e("ipcon", "finishSize:" + finishSize);
//                    if (finishSize == 253) {
//                        isFinish = true;
//                        lastFinishTime = System.currentTimeMillis();
//
//                        Log.e("ipcon", "finishSize:" + finishSize);
//                    }
//                    try {
//                        Thread.sleep(300);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
    }
}